package com.wry.im.handler.v2;

import com.alibaba.fastjson.JSON;
import com.wry.im.entity.Command;
import com.wry.im.entity.Result;
import com.wry.im.server.ChatNettyServer;
import io.netty.channel.ChannelHandlerContext;

/**
 * <h1>  <h1>
 *
 * @author wry
 * @since 2023/4/28 10:39
 */
public class ConnectHandler {

    public static void exec(ChannelHandlerContext channelHandlerContext, Command command) {
        //判断用户是否已上线
        if (ChatNettyServer.USERS.containsKey(command.getNickname())) {
            channelHandlerContext.channel().writeAndFlush(Result.fail("该用户已上线，请换个昵称再试~"));
            //断开连接
            channelHandlerContext.channel().disconnect();
            return;
        }

        ChatNettyServer.USERS.put(command.getNickname(), channelHandlerContext.channel());

        channelHandlerContext.channel().writeAndFlush(Result.success("与服务端建立连接成功"));
        //返回群聊的人
        channelHandlerContext.channel().writeAndFlush(Result.success(JSON.toJSONString(ChatNettyServer.USERS.keySet())));
    }
}
